<?php

/**
 * Created by PhpStorm
 * Author niuyongqiang@kungeek.com
 * Date 2022/2/9 16:23
 */

namespace App\Models;


use Illuminate\Database\Eloquent\Relations\HasMany;


class MessageModel extends BaseModel
{

    /**
     * 关联到模型的数据表
     * @var string
     */
    protected $table = 'info_message';
    public $timestamps = false;

    /**
     * 查询分页
     * @param array $where
     * @param int $limit
     * @param string $field
     * @param string $whereInKey
     * @param array $whereInValue
     * @return array
     */
    public static function getPage(array $where, int $limit, string $field='*', string $whereInKey = '', array $whereInValue = []) : array
    {
        $query = self::query()
            ->selectRaw($field)
            ->where($where);

        if (!empty($whereInKey) && !empty($whereInValue)){
            $query->whereIn($whereInKey, $whereInValue);
        }

        $list = $query->orderBy('id', 'desc')
            ->paginate($limit);

        return $list ? $list->toArray() : [];

    }

    /**
     * 查询分页
     * @param array $where
     * @param int $limit
     * @param string $field
     * @param string $whereInKey
     * @param array $whereInValue
     * @return array
     */
    public static function getPageJoinUser(array $where, int $limit, string $field='*', string $whereInKey = '', array $whereInValue = [], $order = [], $params = []) : array
    {



        $query = self::query()
            ->selectRaw($field)
            ->join('info_user', 'info_user.id', '=', 'info_user_public.user_id')
            ->where($where)
            ->with('admin_msg')
            ->with('cat_1_msg')
            ->with('cat_2_msg')
            ->with('area_msg')
            ->with('city_msg')
            ->with('address_msg');

        //发布方式 1快捷  2标准
        if (!empty($params['content_vip'])){
            if ($params['content_vip'] == 1){
                $query->whereNotNull('info_user_public.content_vip');

            }else{
                $query->whereNull('info_user_public.content_vip');

            }
        }

        if (!empty($whereInKey) && !empty($whereInValue)){
            $query->whereIn($whereInKey, $whereInValue);
        }
        if (!empty($order)){
            $query->orderBy($order[0], $order[1]);
        }
        $query->orderBy('id', 'desc');

        $list = $query->paginate($limit);

        return $list ? $list->toArray() : [];

    }

    public function admin_msg(): HasMany
    {
        return $this->hasMany(SysUserModel::class, 'id', 'admin_id');
    }

    public function cat_1_msg(): HasMany
    {
        return $this->hasMany(TagsModel::class, 'id', 'cat_1');
    }

    public function cat_2_msg(): HasMany
    {
        return $this->hasMany(TagsModel::class, 'id', 'cat_2');
    }

    public function area_msg(): HasMany
    {
        return $this->hasMany(CityChinaModel::class, 'code', 'area');
    }

    public function city_msg(): HasMany
    {
        return $this->hasMany(CityChinaModel::class, 'code', 'city');
    }

    public function address_msg(): HasMany
    {
        return $this->hasMany(CityChinaModel::class, 'code', 'address');
    }

    public function cat_msg(): HasMany
    {
        return $this->hasMany(TableModel::class, 'id', 'cat_1');
    }

    public function admin_name(): HasMany
    {
        return $this->hasMany(SysUserModel::class, 'id', 'admin_id');
    }

    /**
     * 查询分页
     */
    public static function getPageByShow(array $where, int $limit, string $field='*', string $whereInKey = '', array $whereInValue = []) : array
    {
        $query = self::query()
            ->selectRaw($field)
            ->where($where);

        if (!empty($whereInKey) && !empty($whereInValue)){
            $query->whereIn($whereInKey, $whereInValue);
        }

        $list = $query->paginate($limit);

        return $list ? $list->toArray() : [];

    }

    /**
     * 查询分页
     * @param array $where
     * @param int $limit
     * @param string $field
     * @param string $whereInKey
     * @param array $whereInValue
     * @return array
     */
    public static function getPageByOrder(array $where, int $limit, string $field='*', string $whereInKey = '', array $whereInValue = []) : array
    {
        $query = self::query()
            ->from('farm_user as u')
            ->selectRaw($field)
            ->join('farm_order as o', 'o.user_id', '=', 'u.id', 'left')
            ->with('address_message')
            ->where($where);

        if (!empty($whereInKey) && !empty($whereInValue)){
            $query->whereIn($whereInKey, $whereInValue);
        }

        $list = $query
            ->groupBy('u.id')
            ->orderBy('id', 'desc')
            ->paginate($limit);

        return $list ? $list->toArray() : [];

    }



    /**
     * 查询
     * @param array $where
     * @param string $whereInKey
     * @param array $whereInValue
     * @param int $limit
     * @return array|null
     */
    public static function getUserData(array $where = [], string $whereInKey='', array $whereInValue=[], int $limit = 999): ?array
    {
        $query = self::query()
            ->where($where);

        if (!empty($whereInKey) && !empty($whereInValue)){
            $query = $query->whereIn($whereInKey, $whereInValue);
        }

        $user = $query
            ->limit($limit)
            ->get();
        return $user ? $user->toArray() : [];
    }

    /**
     * @param array $where
     * @param string $whereInKey
     * @param array $whereInValue
     * @return array|null
     */
    public static function getUserOne(array $where = [], string $whereInKey='', array $whereInValue=[]): ?array
    {
        $where[] = ['status', '=', '1'];
        $where[] = ['deleted_at', '=', 0];
        $query = self::query()
            ->where($where);

        if (!empty($whereInKey) && !empty($whereInValue)){
            $query = $query->whereIn($whereInKey, $whereInValue);
        }

        $user = $query->first();
        return $user ? $user->toArray() : [];
    }

    /**
     * @param array $where
     * @return array|null
     */
    public function getUserAll(array $where = []): ?array
    {
        $where[] = ['status', '=', '1'];
        $where[] = ['deleted_at', '=', 0];
        $user = self::query()
            ->where($where)
            ->get();
        return $user ? $user->toArray() : [];
    }

    public function roleId(): HasMany
    {
        return $this->hasMany(SysUserRoleModel::class, 'uid', 'id');
    }


    /**
     * 获取一个用户
     * @param $uid
     * @return array
     */
    public static function getOneById($uid): array
    {
        $user = self::query()->find($uid);
        return $user ? $user->toArray() : [];
    }

    /**
     * 获取多个用户
     * @param array $where
     * @param array $whereIn
     * @param string[] $field
     * @return array
     */
    public static function getMore(array $where = [], array $whereIn = [], array $field = ['*']): array
    {
        $user = self::query();
        if (!empty($where)) {
            $user->where($where);
        }
        if (!empty($whereIn)) {
            foreach ($whereIn as $arr) {
                $user->whereIn($arr[0], $arr[1]);
            }
        }
        return $user->select($field)->get()->toArray();
    }

    /**
     * 获取多个用户
     * @param array $where
     * @param array $whereIn
     * @param string $field
     * @return array
     */
    public static function getMoreSelectRaw(array $where = [], array $whereIn = [], string $field = '*'): array
    {
        $user = self::query();
        if (!empty($where)) {
            $user->where($where);
        }
        if (!empty($whereIn)) {
            foreach ($whereIn as $arr) {
                $user->whereIn($arr[0], $arr[1]);
            }
        }
        return $user->selectRaw($field)->get()->toArray();
    }

    /**
     * @param array $where
     * @param string $field
     * @param array $id
     * @return array|null
     */
    public function getDataOne(array $where = [], string $field = '', array $id = []): ?array
    {
        $where[] = ['deleted_at', '=', 0];
        $res = self::query()
            ->where($where);

        if (!empty($id)) {
            $res->whereIn($field, $id);
        }

        return $res->get()->toArray();
    }

    /**
     *
     */
    public static function regUser($data): int
    {
        if (empty($data)) return false;
        $saveData['nickname'] = $data['name'] ?? '';
        $saveData['email'] = $data['email'] ?? '';
        $saveData['mobile'] = $data['mobile'] ?? '';
        $saveData['account'] = $data['account'] ?? '';
//        $saveData['password'] = md5(self::createPassword(12)); //随机生成12位密码长度
        $saveData['created_at'] = time();
        return SysUserModel::query()->insertGetId($saveData);
    }


    /**
     * 生产随机密码
     * @param int $pw_length
     * @return string
     */
    public function createPassword(int $pw_length = 8): string
    {
        $randPwd = '';
        for ($i = 0; $i < $pw_length; $i++) {
            $randPwd .= chr(mt_rand(33, 126));
        }
        return $randPwd;
    }

    /**
     * 根据条件获取用户信息
     * @param $where
     * @param $columns
     * @return array
     */
    public static function getSysUserByWhere($where, $columns): array
    {
        $res = self::query();
        if (!empty($where) && is_array($where)) {
            foreach ($where as $key => $value) {
                if (is_array($value) && !empty($value)) {
                    $res = $res->whereIn($key, $value);
                } else {
                    $res = $res->where($key, $value);
                }
            }
        }

        $res = $res->get($columns);

        return $res ? $res->toArray() : [];
    }

    /**
     * 单条的修改
     * @param array $where
     * @param array $data
     * @return int
     */
    public static function updateSingle(array $where, array $data): int
    {
        if (empty($where) || empty($data))
            return 0;

        return self::query()->where($where)->update($data);

    }

    /**
     * 修改
     * @param array $data
     * @return int
     */
    public static function updateSingleNoWhere(array $data): int
    {
        return self::query()->update($data);

    }

    /**
     * @param array $where
     * @return array|null
     */
    public static function getWechatUserOne(array $where = []): ?array
    {
        $where[] = ['status', '=', '1'];
        $where[] = ['deleted_at', '=', 0];
        $user = self::query()
            ->where($where)
            ->first();
        return $user ? $user->toArray() : [];
    }

    /**
     * @param $where
     * @param $columns
     * @return array
     * 客户信息
     */
    public static function getSysUserMes($where, $columns)
    {
        $res = self::query();
        if (isset($where) && !empty($where) && is_array($where)) {
            foreach ($where as $key => $value) {
                if (is_array($value) && !empty($value)) {
                    $res = $res->whereIn($key, $value);
                } else {
                    $res = $res->where($key, $value);
                }
            }
        }
        $data = $res->select($columns)->get();
        return empty($data) ? [] : $data->toArray();
    }

    /**
     * 新增
     * @param $data
     * @return int
     */
    public static function insertSingle($data):int
    {
        return self::query()->insertGetId($data);
    }

    /**
     * 查询一条
     * @param array $where
     * @param string $whereInKey
     * @param array $whereInValue
     * @return array|null
     */
    public static function getSingle(array $where = [], string $whereInKey='', array $whereInValue=[]): ?array
    {

        $query = self::query()
            ->where($where);

        if (!empty($whereInKey) && !empty($whereInValue)){
            $query = $query->whereIn($whereInKey, $whereInValue);
        }

        $user = $query
            ->orderBy('id', 'desc')
            ->first();
        return $user ? $user->toArray() : [];
    }

    /**
     * 自增
     * @param array $where
     * @param string $key
     * @param string $whereInKey
     * @param array $whereInValue
     * @return int
     */
    public static function addIncrement(array $where = [], string $key = '', string $whereInKey='', array $whereInValue=[]):int
    {
        $query = self::query()
            ->where($where);

        if (!empty($whereInKey) && !empty($whereInValue)){
            $query = $query->whereIn($whereInKey, $whereInValue);
        }

        return $query->increment($key);
    }

    /**
     * 自增
     * @param array $where
     * @param string $key
     * @param string $whereInKey
     * @param array $whereInValue
     * @return int
     */
    public static function addIncrementValue(array $where = [], string $key = '', int $value = 1, string $whereInKey='', array $whereInValue=[], array $extra = []):int
    {
        $query = self::query()
            ->where($where);

        if (!empty($whereInKey) && !empty($whereInValue)){
            $query = $query->whereIn($whereInKey, $whereInValue);
        }

        return $query->increment($key, $value, $extra);
    }

    /**
     * 自减
     * @param array $where
     * @param string $key
     * @param string $whereInKey
     * @param array $whereInValue
     * @return int
     */
    public static function subtractDecrement(array $where = [], string $key = '', string $whereInKey='', array $whereInValue=[]):int
    {
        $query = self::query()
            ->where($where);

        if (!empty($whereInKey) && !empty($whereInValue)){
            $query = $query->whereIn($whereInKey, $whereInValue);
        }

        return $query->decrement($key);
    }

    /**
     * @param array $where
     * @param string $whereInKey
     * @param array $whereInValue
     * @return int
     */
    public static function getCount(array $where=[], string $whereInKey='', array $whereInValue=[]): int
    {

        $query = self::query()
            ->where($where);

        if (!empty($whereInKey) && !empty($whereInValue)){
            $query = $query->whereIn($whereInKey, $whereInValue);
        }

        return $query->count();
    }

}
